import json
from urllib.request import Request,urlopen
from urllib.parse import urlencode
from urllib.error import HTTPError,URLError
import base64
import sys
import socket
import datetime
import os

user='4A968CDA9669EFA7C4C5'
pwd='8QS5Zc3qwhuY1XcnMtzLNc4Sspow77SLTwQHxArw'

def now_time():
    n_time=datetime.datetime.today()
    return n_time.strftime("%Y-%m-%d %H:%M:%S")


def time_print(data):
    print('%s %s' % (now_time(), data))

def http_request(url='', data=None, method='GET', timeout=1, header=None, user=None, pwd=None):
    response_data={}
    response_data['code']=0
    response_data['body']=''

    if method == 'GET':
        if data is not None:
            get_params=urlencode(data)
            final_url=url + "?" + get_params
            url=final_url
        request=Request(url)
    elif method == 'POST':
        if data is not None:
            #data=urlencode(data)
            #post_params=data.encode('ascii')
            #time_print('post_params: %s' % post_params)
            post_params=json.dumps(data).encode('utf8')
        request=Request(url, data=post_params)
    else:
        time_print('method error')
        return response_data

    if user is not None and pwd is not None:
        credentials=('%s:%s' % (user, pwd))
        encoded_credentials = base64.b64encode(credentials.encode('ascii'))
        request.add_header('Authorization', 'Basic %s' % encoded_credentials.decode("ascii"))

    #request.add_header('User-Agent', 'Mozilla/5.0')
    if header is not None:
        for key in header:
            request.add_header(str(key), header[key])

    response=None
    try:
        with urlopen(request, timeout=timeout) as response:
            body=response.read()
            code=200
            response_data['code']=code
            response_data['body']=body.decode(encoding="utf-8")
            time_print('http_request DETAIL: method=%s, timeout=%d, data=%s, '
                          'code=%d, url=%s' % (method, timeout, data, code, url))
    except HTTPError as error:
        time_print('http_request HTTPError, code=%d, reason=%s, url=%s'
                      % (error.code, error.reason, url))
        response_data['code']=error.code
        response_data['body']=error.reason
    except URLError as error:
        time_print('http_request URLError, reason=%s, url=%s' % (error.reason, url))
        response_data['body']=error.reason
    except socket.timeout:
        time_print('http_request socket timed out, url=%s' % url)
        response_data['body']='socket timed out'
    finally:
        if response:
            response.close()
    return response_data


def get_post_payload():
    api='http://172.16.1.129:8080/v2-beta/projects/1a5/services/1s14'
    header={'Content-Type':'application/json'}
    res=http_request(url=api, data=None, method='GET', timeout=5, header=header, user=user, pwd=pwd)
    return res['body']

def service_upgrade():
    current_config=get_post_payload()
    current_config=json.loads(current_config)
    launchConfig=current_config['launchConfig']
    launchConfig['imageUuid']='docker:172.16.1.128/weibo/online-app:63'
    payload={
        'inServiceStrategy': {
            'batchSize': 1,
            'intervalMillis': 2000,
            'launchConfig': launchConfig
        }
    }
    #print(payload)
    api='http://172.16.1.129:8080/v2-beta/projects/1a5/services/1s14?action=upgrade'
    header={'Content-Type':'application/json'}
    res=http_request(url=api, data=payload, method='POST', timeout=5, header=header, user=user, pwd=pwd)
    print(res['body'])

def service_finishupgrade():
    api='http://172.16.1.129:8080/v2-beta/projects/1a5/services/1s14?action=finishupgrade'
    header={'Content-Type':'application/json'}
    res=http_request(url=api, data=[], method='POST', timeout=5, header=header, user=user, pwd=pwd)
    print(res['body'])

def service_rollback():
    api='http://172.16.1.129:8080/v2-beta/projects/1a5/services/1s14?action=rollback'
    header={'Content-Type':'application/json'}
    res=http_request(url=api, data=[], method='POST', timeout=5, header=header, user=user, pwd=pwd)
    print(res['body'])

service_rollback()
#service_finishupgrade()
#service_upgrade()
#print(http_request(url='http://i.sunmingchao.com/_prt.php', data={'kkk':'v', 'data':{'a':'b'}}, method='POST', timeout=5))





